package com.gitee.feizns.web.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author feizns
 * @since 2019/4/14
 */
public class ExcelUtils {

    /**
     * 读取
     * @param is
     * @return
     */
    public static Sheet read(InputStream is) {
        ExcelReaderListener erl = new ExcelReaderListener();
        EasyExcel.read(is, erl).sheet().doRead();
        return new Sheet(erl.titles, erl.data);
    }

    /**
     * 写入
     * @param os
     * @param sheet
     */
    public static void write(OutputStream os, Sheet sheet) {
        List<List<Object>> lists = sheet.data;
        lists.add(0, sheet.titles);
        EasyExcel.write(os).sheet(0).doWrite(lists);
    }

    public static class Sheet {

        /**
         * 标题
         */
        public List<Object> titles;

        /**
         * 数据
         */
        public List<List<Object>> data;

        public Sheet(List<Object> titles, List<List<Object>> data) {
            this.titles = titles;
            this.data = data;
        }
    }

    public static class ExcelReaderListener extends AnalysisEventListener<Map> {

        List<Object> titles = new LinkedList<>();

        List<List<Object>> data = new LinkedList<>();

        @Override
        public void invoke(Map data, AnalysisContext context) {
            LinkedList<Object> list = new LinkedList<>();
            data.forEach((k, v) -> list.add(v));
            this.data.add(list);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {

        }

        @Override
        public void invokeHeadMap(Map headMap, AnalysisContext context) {
            headMap.forEach((k, v) -> titles.add(v));
        }

    }

}
